package com.apache.jwt;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>@Description http请求帮助类
 * <p>@version v1.0
 */
public class PostHttps {

    private static PostHttps instance;

    private Logger logger = Logger.getLogger(PostHttps.class);

    private PostHttps() {
    }

    public static PostHttps newInstance() {
        if (null == instance) {
            instance = new PostHttps();
        }
        return instance;
    }

    /**
     * post http 请求，接受返回的结果xml文档
     *
     * @param url webservice地址
     * @return xml类型字符串
     */
    public String getHttp(String url, NameValuePair[] paras, String method) {
        String line = "";
        HttpClient client = null;
        if (null == paras || paras.length == 0) {
            return "";
        }
        try {
            HttpResponse response = null;
            client = new DefaultHttpClient();
            if ("GET".equalsIgnoreCase(method)) {
                String params = "";
                for (int i = 0; i < paras.length; i++) {
                    params += paras[i].getName() + "=" + paras[i].getValue() + "&";
                }
                HttpGet getMethod = new HttpGet(url + "?" + params);
                response = client.execute(getMethod);
            } else {
                HttpPost post = new HttpPost(url);
                // 创建参数队列
                List<NameValuePair> formparams = new ArrayList<NameValuePair>(3);
                for (int i = 0; i < paras.length; i++) {
                    formparams.add(paras[i]);
                }
                //参数转码
                UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                post.setEntity(uefEntity);
                response = client.execute(post);
            }
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                line = EntityUtils.toString(entity);
                entity.consumeContent();
            }
        } catch (Exception e) {
            logger.error(e);
        } finally {
            if (null != client)
                client.getConnectionManager().shutdown();
        }
        return line;
    }

    /**
     * 公共方法
     * post http 请求，接受返回的结果xml文档
     *
     * @param method POST/GET
     * @return xml类型字符串
     */
    public String getHttpsForStl(String httpsurl, NameValuePair[] paras, String method) {
        String line = "";
        SSLClient client = null;
        try {
            if (null == paras || paras.length == 0) {
                return "";
            }
            client = new SSLClient();
            HttpResponse response = null;
            if ("GET".equals(method.toUpperCase())) {
                String params = "";
                for (int i = 0; i < paras.length; i++) {
                    params += paras[i].getName() + "=" + paras[i].getValue() + "&";
                }
                HttpGet get = new HttpGet(httpsurl + "?" + params);
                response = client.execute(get);
            } else {
                HttpPost post = new HttpPost(httpsurl);
                // 创建参数队列
                List<NameValuePair> formparams = new ArrayList<NameValuePair>(3);
                for (int i = 0; i < paras.length; i++) {
                    formparams.add(paras[i]);
                }
                //参数转码
                UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                post.setEntity(uefEntity);
                response = client.execute(post);
            }
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                line = EntityUtils.toString(entity);
                entity.consumeContent();
            }
        } catch (Exception e) {
            logger.error(e);
        } finally {
            if (null != client) { // 关闭连接，腾出内存空间
                client.getConnectionManager().shutdown();
            }
        }
        return line;
    }

    class SSLClient extends DefaultHttpClient {

        public SSLClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLSv1.2");
            TrustManager[] tm = { new MyX509TrustManager() };
            ctx.init(null, tm, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            this.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf, 443));
        }
    }

}